<template>
  <el-card class="good-container">
    <template #header>
      <div class="header">
        <el-input
          class="search"
          v-model="searchVal.keyWord"
          size="small"
          placeholder="输入商品名称"
          style="width: 200px;"
        />
        <el-select v-model="searchVal.status" placeholder="请选择商品上架状态" class="search">
          <el-option label="已上架" :value="0"/>
          <el-option label="已下架" :value="1"/>
        </el-select>
        <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
        <el-button type="" :icon="RefreshRight" @click="reset">重置</el-button>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增商品</el-button>
      </div>
    </template>
    <el-table
      :load="state.loading"
      :data="state.tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column
        prop="goodsId"
        label="商品编号"
      >
      </el-table-column>
      <el-table-column
        prop="goodsName"
        label="商品名"
      >
      </el-table-column>
      <el-table-column
        prop="goodsIntro"
        label="商品简介"
      >
      </el-table-column>
      <el-table-column
        label="商品图片"
        width="150px"
      >
        <template #default="scope">
          <img style="width: 100px; height: 100px;" :key="scope.row.goodsId" :src="$filters.prefix(scope.row.goodsCoverImg)" alt="商品主图">
        </template>
      </el-table-column>
      <el-table-column
        prop="stockNum"
        label="商品库存"
      >
      </el-table-column>
      <el-table-column
        prop="sellingPrice"
        label="商品售价"
      >
      </el-table-column>
      <el-table-column
        label="上架状态"
      >
        <template #default="scope">
          <span style="color: green;" v-if="scope.row.goodsSellStatus == 0">销售中</span>
          <span style="color: red;" v-else>已下架</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        width="200"
      >
        <template #default="scope">
          <a style="cursor: pointer; margin-right: 10px" @click="handleEdit(scope.row.goodsId)">修改</a>
          <a style="cursor: pointer; margin-right: 10px" @click="handleView(scope.row)">详情</a>
          <a style="cursor: pointer; margin-right: 10px" v-if="scope.row.goodsSellStatus == 0" @click="handleStatus(scope.row.goodsId, 1)">下架</a>
          <a style="cursor: pointer; margin-right: 10px" v-else @click="handleStatus(scope.row.goodsId, 0)">上架</a>
          <el-popconfirm title="确认删除该条商品吗？" @confirm="deleteItem(scope.row)">
            <template #reference>
              <a style="cursor: pointer; margin-right: 10px" >删除</a>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="state.total"
      :page-size="state.pageSize"
      :current-page="state.currentPage"
      @current-change="changePage"
    />
  </el-card>
  <el-dialog v-model="dialogTableVisible" title="商品详情">
    <el-card class="add-container">
      <el-form  label-width="100px" class="goodForm" disabled>
        <el-form-item label="商品分类">
          <el-select  :placeholder="goodsState.defaultCate" v-model="goodsState.categoryId" style="width: 300px;">
            <el-option
              v-for="item in goodsState.options"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" >
          <el-input style="width: 300px" v-model="goodsState.goodForm.goodsName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品简介">
          <el-input style="width: 300px" type="textarea" v-model="goodsState.goodForm.goodsIntro" placeholder="请输入商品简介(100字)"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" >
          <el-input type="number" min="0" style="width: 300px" v-model="goodsState.goodForm.originalPrice" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品售卖价" >
          <el-input type="number" min="0" style="width: 300px" v-model="goodsState.goodForm.sellingPrice" placeholder="请输入商品售价"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" >
          <el-input type="number" min="0" style="width: 300px" v-model="goodsState.goodForm.stockNum" placeholder="请输入商品库存"></el-input>
        </el-form-item>
        <el-form-item label="商品标签">
          <el-input style="width: 300px" v-model="goodsState.goodForm.tag" placeholder="请输入商品小标签"></el-input>
        </el-form-item>
        <el-form-item label="上架状态" >
          <el-radio-group v-model="goodsState.goodForm.goodsSellStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="商品主图" >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;"  :src="goodsState.goodForm.goodsCoverImg" class="avatar">
        </el-form-item>
        <el-form-item label="详情内容">
          <div ref='editor'></div>
        </el-form-item>
      </el-form>
    </el-card>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, getCurrentInstance ,ref} from 'vue'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Search, RefreshRight } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const editor = ref(null)
const app = getCurrentInstance()
const { goTop } = app.appContext.config.globalProperties
const router = useRouter()
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10 // 分页大小
})
const searchVal = reactive({
  status:'',
  keyWord:''
})
const dialogTableVisible =ref(false)
const goodsState = reactive({
  defaultCate: '请选择商品分类',
  goodForm: {
    goodsName: '',
    goodsIntro: '',
    originalPrice: '',
    sellingPrice: '',
    stockNum: '',
    goodsSellStatus: '0',
    goodsCoverImg: '',
    tag: ''
  },
  options:[],
  categoryId: '',
  category: {
    lazy: false,
    checkStrictly: true,
  }
})
onMounted(() => {
  getGoodList()
})
// 获取轮播图列表
const getGoodList = () => {
  state.loading = true
  axios.get('/goods/list', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize
    }
  }).then(res => {
    state.tableData = res.list
    state.total = res.totalCount
    state.currentPage = res.currPage
    state.loading = false
    goTop && goTop()
  })
  axios.get('/categories', {
    params: {
      pageNumber: 1,
      pageSize: 1000,
      categoryLevel: 1,
      parentId:0
    }
  }).then(res => {
    const list = res.list
    state.options = list 
  })
  
}
const handleAdd = () => {
  router.push({ path: '/add' })
}
const reset =()=>{
  searchVal.keyWord = ''
  searchVal.status = ''
  search()
}
const search =()=>{
  Object.assign(state,{
    loading:true,
    tableData:[],
    total:0,
    currentPage : 1,
    pageSize : 10
  })
 
  axios.get('/goods/list', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
      goodsName:searchVal.keyWord,
      goodsSellStatus:searchVal.status
    }
  }).then(res => {
    state.tableData = res.list
    state.total = res.totalCount
    state.currentPage = res.currPage
    state.loading = false
    goTop && goTop()
  })
}

const handleEdit = (id) => {
  router.push({ path: '/add', query: { id } })
}
const handleView = (goods) => {
  dialogTableVisible.value = true
  goodsState.goodForm = {
    goodsName: goods.goodsName,
    goodsIntro: goods.goodsIntro,
    originalPrice: goods.originalPrice,
    sellingPrice: goods.sellingPrice,
    stockNum: goods.stockNum,
    goodsSellStatus: String(goods.goodsSellStatus),
    // goodsCoverImg: proxy.$filters.prefix(goods.goodsCoverImg),
    tag: goods.tag
  }
  state.categoryId = goods.goodsCategoryId
}
const changePage = (val) => {
  state.currentPage = val
  getGoodList()
}
const handleStatus = (id, status) => {
  axios.put(`/goods/status/${status}`, {
    ids: id ? [id] : []
  }).then(() => {
    ElMessage.success('修改成功')
    getGoodList()
  })
}
const deleteItem =(item) =>{
  axios.post('deleteGoods', {
    goodsId: item.goodsId
  }).then(() => {
    ElMessage.success('删除成功')
      search()
  })
}
</script>

<style scoped>
  .good-container {
    min-height: 100%;
    .header{
      display: flex;
      .search{
        margin-right: 10px;
      }
    }
  }
  .el-card.is-always-shadow {
    min-height: 100%!important;
  }
</style>
